<template>
  <div class="profile-container">
    <div class="page-header">
      <h1>个人设置</h1>
      <p>管理您的账户信息和安全设置</p>
    </div>

    <a-row :gutter="24">
      <!-- 基本信息 -->
      <a-col :xs="24" :lg="12">
        <a-card title="基本信息" class="info-card">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item label="邮箱">
              {{ userInfo.email }}
            </a-descriptions-item>
            <a-descriptions-item label="管理员类型">
              <a-tag :color="getTypeColor(userInfo.type)">
                {{ getTypeText(userInfo.type) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="账户状态">
              <a-tag :color="userInfo.is_enable ? 'green' : 'red'">
                {{ userInfo.is_enable ? '启用' : '禁用' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ formatTime(userInfo.created_at) }}
            </a-descriptions-item>
            <a-descriptions-item label="最后登录">
              {{ formatTime(new Date()) }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>

      <!-- 修改密码 -->
      <a-col :xs="24" :lg="12">
        <a-card title="修改密码" class="password-card">
          <a-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            layout="vertical"
            @finish="handlePasswordChange"
          >
            <a-form-item label="当前密码" name="oldPassword">
              <a-input-password 
                v-model:value="passwordForm.oldPassword" 
                placeholder="请输入当前密码"
              />
            </a-form-item>
            
            <a-form-item label="新密码" name="newPassword">
              <a-input-password 
                v-model:value="passwordForm.newPassword" 
                placeholder="请输入新密码"
              />
            </a-form-item>
            
            <a-form-item label="确认新密码" name="confirmPassword">
              <a-input-password 
                v-model:value="passwordForm.confirmPassword" 
                placeholder="请再次输入新密码"
              />
            </a-form-item>
            
            <a-form-item>
              <a-button 
                type="primary" 
                html-type="submit" 
                :loading="passwordLoading"
                block
              >
                <LockOutlined />
                修改密码
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>

    <!-- 安全提示 -->
    <a-card title="安全提示" class="security-tips">
      <a-alert
        message="账户安全建议"
        type="info"
        show-icon
      >
        <template #description>
          <ul>
            <li>定期更换密码，建议每3个月更换一次</li>
            <li>密码应包含大小写字母、数字和特殊字符</li>
            <li>不要在多个平台使用相同密码</li>
            <li>发现异常登录活动请及时联系系统管理员</li>
            <li>退出系统时请点击注销按钮，不要直接关闭浏览器</li>
          </ul>
        </template>
      </a-alert>
    </a-card>

    <!-- 操作记录 -->
    <a-card title="最近操作" class="activity-card">
      <a-list
        :data-source="recentActivities"
        size="small"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #avatar>
                <a-avatar :style="{ backgroundColor: item.color }">
                  <component :is="item.icon" />
                </a-avatar>
              </template>
              <template #title>
                {{ item.action }}
              </template>
              <template #description>
                {{ item.time }}
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { authApi, managerApi } from '@/api'
import {
  LockOutlined,
  LoginOutlined,
  SettingOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

export default defineComponent({
  name: 'ProfileView',
  components: {
    LockOutlined,
    LoginOutlined,
    SettingOutlined,
    UserOutlined
  },
  setup() {
    const passwordLoading = ref(false)
    const passwordFormRef = ref()
    
    // 用户信息
    const userInfo = reactive({
      email: '',
      type: 1,
      is_enable: true,
      created_at: ''
    })
    
    // 密码表单
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 密码验证规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
        {
          validator: (rule, value) => {
            if (value === passwordForm.oldPassword) {
              return Promise.reject('新密码不能与当前密码相同')
            }
            return Promise.resolve()
          },
          trigger: 'blur'
        }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value) => {
            if (value !== passwordForm.newPassword) {
              return Promise.reject('两次输入的密码不一致')
            }
            return Promise.resolve()
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 最近操作记录
    const recentActivities = ref([
      {
        id: 1,
        action: '登录系统',
        time: '2分钟前',
        icon: LoginOutlined,
        color: '#1890ff'
      },
      {
        id: 2,
        action: '查看管理员列表',
        time: '10分钟前',
        icon: UserOutlined,
        color: '#52c41a'
      },
      {
        id: 3,
        action: '修改个人设置',
        time: '1小时前',
        icon: SettingOutlined,
        color: '#faad14'
      },
      {
        id: 4,
        action: '登录系统',
        time: '昨天 14:30',
        icon: LoginOutlined,
        color: '#1890ff'
      }
    ])
    
    // 获取用户信息
    const getUserInfo = () => {
      const userStr = localStorage.getItem('admin_user')
      if (userStr) {
        const user = JSON.parse(userStr)
        userInfo.email = user.email
        userInfo.type = user.type
        userInfo.is_enable = user.is_enable
        userInfo.created_at = user.created_at
      }
    }
    
    // 修改密码
    const handlePasswordChange = async () => {
      passwordLoading.value = true
      try {
        // 注意：这里使用当前用户ID，需要从localStorage获取
        const userStr = localStorage.getItem('admin_user')
        if (!userStr) {
          message.error('用户信息获取失败')
          return
        }
        
        const user = JSON.parse(userStr)
        const result = await managerApi.changePassword({
          id: user.id,
          password: passwordForm.newPassword
        })
        
        if (result.code === null) {
          message.success(result.msg || '密码修改成功，请重新登录')
          // 跳转到登录页
          setTimeout(() => {
            window.location.href = '/login'
          }, 1500)
        } else if (result.code === -1) {
          message.error(result.msg || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        message.error('密码修改失败，请检查当前密码是否正确')
      } finally {
        passwordLoading.value = false
      }
    }
    
    // 获取类型颜色
    const getTypeColor = (type) => {
      const colorMap = {
        1: 'red',
        2: 'blue',
        3: 'green',
        4: 'orange'
      }
      return colorMap[type] || 'default'
    }
    
    // 获取类型文本
    const getTypeText = (type) => {
      const textMap = {
        1: '超级管理员',
        2: '普通管理员',
        3: '编辑员',
        4: '查看员'
      }
      return textMap[type] || '未知'
    }
    
    // 格式化时间
    const formatTime = (time) => {
      if (!time) return '-'
      return new Date(time).toLocaleString('zh-CN')
    }
    
    onMounted(() => {
      getUserInfo()
    })
    
    return {
      userInfo,
      passwordForm,
      passwordRules,
      passwordFormRef,
      passwordLoading,
      recentActivities,
      handlePasswordChange,
      getTypeColor,
      getTypeText,
      formatTime
    }
  }
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 22px;
  font-weight: 600;
  color: #000;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.info-card,
.password-card,
.security-tips,
.activity-card {
  margin-bottom: 20px;
}

.security-tips ul {
  margin: 0;
  padding-left: 20px;
}

.security-tips li {
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>